package com.rcm.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.ibatis.session.SqlSession;

import com.rcm.dao.CoursesinfoMapper;
import com.rcm.dao.StudentinfoMapper;
import com.rcm.dao.TeacherinfoMapper;
import com.rcm.model.Coursesinfo;
import com.rcm.model.Studentinfo;
import com.rcm.model.Teacherinfo;
import com.rcm.dao.StudentinfoMapper;
import com.rcm.utility.MyBatisTool;


@WebServlet("/Studentinfocontroller/*")
public class Studentinfocontroller extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static StudentinfoMapper mapper = null;

	static {
		SqlSession session = MyBatisTool.getSession();

		mapper = session.getMapper(StudentinfoMapper.class);
	}


	//获取url
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String uri = request.getRequestURI();
		int idx = uri.lastIndexOf("/");
		String methodName = uri.substring(idx + 1);
		System.out.println(methodName);

		try {
			Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class,
					HttpServletResponse.class);
			method.invoke(this, request, response);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	//注册判断邮箱验证码是否输入正确
	public void RegistServlet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException, IllegalAccessException, InvocationTargetException {

		String sessionCode = (String) request.getSession().getAttribute("code");
		System.out.println(sessionCode);
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		if (sessionCode != null) {
			// 获取页面提交的验证码
			String inputCode = request.getParameter("code");
			System.out.println("页面提交的验证码:" + inputCode);
			if (sessionCode.toLowerCase().equals(inputCode.toLowerCase())) {
				//如果验证码正确则跳转到add
				Add(request, response);
			} else {
				// 验证失败
				out.print("<script language='javascript'>alert('邮箱验证码错误');window.location.href='../register.jsp';</script>");
				// request.getRequestDispatcher("/fail.jsp").forward(request, response);
			}
		} else {
			// 验证失败
			out.print("<script language='javascript'>alert('邮箱验证码错误');window.location.href='../register.jsp';</script>");
			// request.getRequestDispatcher("/fail.jsp").forward(request, response);
		}
		// 移除session中的验证码
		request.removeAttribute("code");
	}
	//注册 
	public void Add(HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			response.setContentType("text/html;charset=utf-8");
			PrintWriter out = response.getWriter();
			Map<String, String[]> map = request.getParameterMap();
			Studentinfo studentinfo = new Studentinfo();
			BeanUtils.populate(studentinfo, map);
			System.out.println(studentinfo);
			mapper.insert(studentinfo);
			out.print("<script language='javascript'>alert('注册成功，返回登录');window.location.href='../index.jsp';</script>");
		} catch (Exception e) {
			response.sendRedirect("error.jsp");
			return;
		}
	}
	//判断用户名是否已存在
	public void sId(HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			response.setContentType("text/html;charset=utf-8");
			PrintWriter out = response.getWriter();
			String sid=request.getParameter("sid");
			List<Studentinfo> list = mapper.selectAll();
			for (Studentinfo c : list) {
				if(sid.equals(c.getSid())) {
					out.print("1");
					return;
				}
			}
			
			
		} catch (Exception e) {
			response.sendRedirect("error.jsp");
			return;
		}
	}
	

	//添加选课
	public void AddCoursess(HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			SqlSession session = MyBatisTool.getSession();
			CoursesinfoMapper mapper = session.getMapper(CoursesinfoMapper.class);
			Coursesinfo coursesinfo = new Coursesinfo();
			String[] Coursess = request.getParameterValues("Coursess");
			coursesinfo.setChoice_a(Coursess[0]);
			coursesinfo.setChoice_b(Coursess[1]);
			coursesinfo.setChoice_c(Coursess[2]);
			coursesinfo.setChoice_d(Coursess[3]);
			coursesinfo.setChoice_e(Coursess[4]);
			coursesinfo.setChoice_f(Coursess[5]);
			Studentinfo c = (Studentinfo) request.getSession().getAttribute("c");
			coursesinfo.setSid(c.getSid());
			coursesinfo.setName(c.getName());
			Date date= new Date();
			SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time=df.format(date);
			coursesinfo.setCdate(time);
			coursesinfo.setCip(request.getRemoteAddr());
			System.out.println(coursesinfo);
			mapper.insert(coursesinfo);
			//记录选过课
			request.getSession().setAttribute("coursess", "true");
			session.close();
			//选课成功后跳转coursesresult 选课结果
			coursesresult(request,response);
		} catch (Exception e) {
			response.setContentType("text/html;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print(
					"<script language='javascript'>alert('选课失败，请重新选择!');window.location='/ElectiveSystem/Studentinfocontroller/coursess';</script>");
			return;
		}

	}

	//导航栏的（选课），如果有选课的记录则跳转到选课结果，如果没有选课记录则跳转到选课界面
	public void coursess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String coursess =(String) request.getSession().getAttribute("coursess");
		if(coursess=="true") {
			//选课结果
			coursesresult(request,response);
		}else {
			request.getRequestDispatcher("/addcoursess.jsp").forward(request, response);
		}



	}
	//选课结果
	public void coursesresult(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Studentinfo c = (Studentinfo) request.getSession().getAttribute("c");
		SqlSession session=MyBatisTool.getSession();
		CoursesinfoMapper mapper=session.getMapper(CoursesinfoMapper.class);
		
		Coursesinfo r=mapper.selectByPrimaryKey(c.getSid());
		session.close();
		System.out.println(r);
		request.getSession().setAttribute("c2", r);
		request.getRequestDispatcher("/courses.jsp").forward(request, response);
	}

	//修改选课记录
	public void update(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try {
			Coursesinfo coursesinfo = new Coursesinfo(null, null, null, null, null, null, null, null, null, null);
			String[] Coursess = request.getParameterValues("Coursess");
			coursesinfo.setChoice_a(Coursess[0]);
			coursesinfo.setChoice_b(Coursess[1]);
			coursesinfo.setChoice_c(Coursess[2]);
			coursesinfo.setChoice_d(Coursess[3]);
			coursesinfo.setChoice_e(Coursess[4]);
			coursesinfo.setChoice_f(Coursess[5]);
			Studentinfo c = (Studentinfo) request.getSession().getAttribute("c");
			String sid =c.getSid();		
			String name=c.getName();
			System.out.println(c);
			Date date= new Date();
			SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time=df.format(date);
			coursesinfo.setCdate(time);
			coursesinfo.setCip(request.getRemoteAddr());
			coursesinfo.setSid(sid);
			coursesinfo.setName(name);
			System.out.println(coursesinfo);
			SqlSession session = MyBatisTool.getSession();
			CoursesinfoMapper mapper = session.getMapper(CoursesinfoMapper.class);
			mapper.updateByPrimaryKey(coursesinfo);
			session.close();

			//修改成功后跳转到选课结果
			coursesresult(request,response);
		} catch (Exception e) {
			response.setContentType("text/html;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print(
					"<script language='javascript'>alert('选课失败，请重新选择!');window.location='/ElectiveSystem/Studentinfocontroller/coursess';</script>");
			return;
		}
	}


	//更新学生个人资料
	public void updatestudentinfo(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		String gradeclass =request.getParameter("gradeclass");
		String age=request.getParameter("age");
		Studentinfo c = (Studentinfo) request.getSession().getAttribute("c");
		String sid =c.getSid();		
		Studentinfo studentinfo = new Studentinfo();
		studentinfo.setGradeclass(gradeclass);
		studentinfo.setAge(age);
		studentinfo.setSid(sid);
		System.out.println(studentinfo);
		SqlSession session = MyBatisTool.getSession();
		StudentinfoMapper mapper = session.getMapper(StudentinfoMapper.class);
		mapper.updateByPrimaryKey(studentinfo); 
		List<Studentinfo> list=mapper.selectAll();
		for(Studentinfo d:list){
			if(sid.equals(d.getSid())) {
				request.getSession().setAttribute("c", d);
				System.out.println(d);
			}
		}
		session.close();
		request.getRequestDispatcher("/studentInfo.jsp").forward(request, response);
	}

	//更新学生密码
	public void updatepassword(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		String sessionCode = (String) request.getSession().getAttribute("code");
		System.out.println(sessionCode);
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		if (sessionCode != null) {
			// 获取页面提交的验证码
			String inputCode = request.getParameter("code");
			System.out.println("页面提交的验证码:" + inputCode);
			if (sessionCode.toLowerCase().equals(inputCode.toLowerCase())) {
				System.out.println("验证成功");
				String nowpass =request.getParameter("nowpass");
				Studentinfo c = (Studentinfo) request.getSession().getAttribute("c");
				String sid =c.getSid();		
				Studentinfo studentinfo = new Studentinfo();
				studentinfo.setPassword(nowpass);
				studentinfo.setSid(sid);
				System.out.println(studentinfo);
				SqlSession session = MyBatisTool.getSession();
				StudentinfoMapper mapper = session.getMapper(StudentinfoMapper.class);
				mapper.updatepassword(studentinfo);
				session.close();
				out.print("<script language='javascript'>alert('修改成功，请重新登录!');window.location='/ElectiveSystem/index.jsp';</script>");
				return;

			} else {
				// 验证失败
				out.print(
						"<script language='javascript'>alert('邮箱验证码错误');window.location.href='../editpassword.jsp';</script>");
			}
		} else {
			// 验证失败
			out.print(
					"<script language='javascript'>alert('邮箱验证码错误');window.location.href='../editpassword.jsp';</script>");
		}
		// 移除session中的验证码
		request.removeAttribute("code");

	}
	

	



	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
